package com.w.picture.api.aliyunai;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.w.picture.api.aliyunai.model.ImageOutPaintingRequest;
import com.w.picture.api.aliyunai.model.ImageOutPaintingResponse;
import com.w.picture.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.w.picture.exception.BusinessException;
import com.w.picture.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author wzp
 * @since 2025/1/25
 */
@Slf4j
@Component
public class AliYunAiApi {
    @Value("${aliyunai.apiKey}")
    private String apiKey;

    // 创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    // 查询任务状态
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";


    /**
     * 创建扩图任务
     * https://help.aliyun.com/zh/model-studio/developer-reference/image-scaling-api?utm_content=m_1000400274#dc02de8e5earc
     * @param request 请求体
     * @return
     */

    public ImageOutPaintingResponse createImageScalingTask(ImageOutPaintingRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(),"扩图参数为空");
        }
        // 构建URL
        String url = CREATE_OUT_PAINTING_TASK_URL;

        // 设置请求头
        HttpRequest post = HttpRequest.post(url)
                .header("Authorization", "Bearer " + apiKey)
                .header("X-DashScope-Async", "enable")
                .header("Content-Type", "application/json");

        // 将请求体转换为JSON字符串
        String requestBody = JSONUtil.toJsonStr(request);

        // 发送POST请求
        HttpResponse response = post.body(requestBody).execute();
        if (response.isOk()) {
            // 解析响应
            log.info("创建扩图任务结果: {}", response.body());
            JSONObject jsonResponse = JSONUtil.parseObj(response.body());
            return JSONUtil.toBean(jsonResponse, ImageOutPaintingResponse.class);
        } else {
            log.error("创建扩图任务失败: {}", response.body());
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(),"创建扩图任务失败: " + response.getStatus() + ", " + response.body());
        }
    }


    /**
     * 查询任务结果
     * @param taskId 任务ID
     * @return
     */
    public GetOutPaintingTaskResponse getTaskResult(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), "任务ID 不能为空");
        }

        // 构建URL
        String url = String.format(GET_OUT_PAINTING_TASK_URL, taskId);

        // 设置请求头
        HttpRequest get = HttpRequest.get(url)
                .header("Authorization", "Bearer " + apiKey);

        // 发送GET请求
        HttpResponse response = get.execute();
        if (response.isOk()) {
            // 解析响应
            log.info("查询任务结果: {}", response.body());
            JSONObject jsonResponse = JSONUtil.parseObj(response.body());
            return JSONUtil.toBean(jsonResponse, GetOutPaintingTaskResponse.class);
        } else {
            log.error("查询任务结果失败: {}", response.body());
            throw new RuntimeException("查询任务结果失败: " + response.getStatus() + ", " + response.body());
        }
    }
}

